<template>
  <div class="card-container" style="padding-top: 15px; padding-bottom: 20px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['departmentWaterResources:personnel:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['departmentWaterResources:personnel:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="personnelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" width="120" align="center" prop="name">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="附件名称" align="center" prop="resName"/>
      <el-table-column label="附件类型" align="center" prop="fileSuffix"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['departmentWaterResources:personnel:edit']">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="tips">*重大项目及省拨经费30万元及以上的项目，需要填写并上传可行性研究报告，相关模板请在登录页面下载。</div>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <div style="display: flex; justify-content: flex-end; margin-top: 60px" v-if="route.query.type !== 'look'">
      <el-button type="primary" @click="onSubmit(0)">保存草稿</el-button>
      <el-button type="primary" @click="onSubmit(1)">完成</el-button>
      <el-button @click="onCancel">取消</el-button>
    </div>
    <!-- 添加或修改项目人员信息对话框 -->
    <el-dialog :title="title" v-model="open" width="400px" append-to-body>
      <el-form ref="personnelRef" :model="form" :rules="rules" label-width="auto">
        <el-row class="mb8">
          <el-col :span="24">
            <el-form-item label="" prop="fileList">
              <MyFileUpload v-model="form.fileList" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {listPersonnel,personnelAddOrUpdate, getPersonnel, delPersonnel, addPersonnel, updatePersonnel} from "@/api/departmentWaterResources/personnel";
import {useRoute} from "vue-router";
import {addOrUpdateFile, getFile} from "@/api/departmentWaterResources/project.js";
import MyFileUpload from "@/components/MyFileUpload/index.vue";

const {proxy} = getCurrentInstance();
const {sys_user_sex, education_level} = proxy.useDict('sys_user_sex', 'education_level');
const route = useRoute();

const personnelList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

/** 查询项目人员信息列表 */
function getList() {
  loading.value = true;
  getFile({...queryParams.value, sourceId: route.query.id, sourceType: 1}).then(response => {
    personnelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    sex: null,
    nation: null,
    birthday: null,
    idcard: null,
    professional: null,
    researchExpertise: null,
    edu: null,
    signature: null,
    graduationSchool: null,
    email: null,
    workUnit: null,
    contactPhone: null,
    address: null,
    postcode: null,
    fax: null,
    projectTrak: null,
    projectId: null,
    sort: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remarks: null,
    delFlag: null
  };
  proxy.resetForm("personnelRef");
}

const onSubmit = (type) => {
  personnelList.value.forEach((item) => {
    item.sourceType = '0'
    item.sourceId = route.query.id
  })
  addOrUpdateFile({resourceList: personnelList.value, projectId: route.query.id, saveType: type + 1}).then(response => {
    if (type === 0) {
      proxy.$modal.msgSuccess("保存成功");
    } else {
      // emit('activeNext', 'tab4')
      proxy.$modal.msgSuccess("保存成功");
      onCancel()
    }
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加项目人员信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  // reset();
  // const _id = row.id || ids.value
  // getPersonnel(_id).then(response => {
  console.log(row)
  form.value = {...row};
  open.value = true;
  title.value = "修改项目人员信息";
  // });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["personnelRef"].validate(valid => {
    if (valid) {
      if (title.value === "修改项目人员信息") {
        // updatePersonnel(form.value).then(response => {
        //   proxy.$modal.msgSuccess("修改成功");
        //   open.value = false;
        //   getList();
        // });
        let index = personnelList.value.findIndex(item => item.idcard === form.value.idcard)
        personnelList.value[index] = form.value
        console.log(personnelList.value, index)
        open.value = false;
      } else {
        // addPersonnel(form.value).then(response => {
        //   proxy.$modal.msgSuccess("新增成功");
        //   open.value = false;
        //   getList();
        // });
        form.value.fileList.forEach((item) => {
          personnelList.value.push(item)
        })
        open.value = false;
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  // const _ids = row.id || ids.value;
  // proxy.$modal.confirm('是否确认删除项目人员信息编号为"' + _ids + '"的数据项？').then(function () {
  //   return delPersonnel(_ids);
  // }).then(() => {
  //   getList();
  //   proxy.$modal.msgSuccess("删除成功");
  // }).catch(() => {
  // });
  let index = personnelList.value.findIndex(item => item.idcard === row.idcard)
  personnelList.value.splice(index, 1)
}

function onCancel() {
  const obj = { path: "/project/infoManagement" };
  proxy.$tab.closeOpenPage(obj);
}

getList();
</script>

<style scoped lang="scss">
.tips {
  color: red;
  margin-top: 20px;
}
</style>
